package com.xpchenfrank.test.jdk8;

import groovy.util.MapEntry;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xpchen
 * @time 2018/8/17 15:38
 * @Description
 * @copyright Wuxi Yazuo ,Ltd.copyright 2015-2025
 */
@Data
public class Groupingby {

    public static void main(String[] args) {

        List<Item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
        );

        //group by price
        Map<BigDecimal, List<Item>> groupByPriceMap =
                items.stream().collect(Collectors.groupingBy(Item::getPrice));

        System.out.println(groupByPriceMap);

        // group by price, uses 'mapping' to convert List<Item> to Set<String>
        Map<BigDecimal, Set<String>> result =
                items.stream().collect(
                        Collectors.groupingBy(Item::getPrice,
                                Collectors.mapping(Item::getName, Collectors.toSet())
                        )
                );

        System.out.println("1111" + result);

        for(Map.Entry<BigDecimal, Set<String>> mapEntry : result.entrySet()) {
            System.out.println("key is " + mapEntry.getKey());
            Set<String> keyVal = mapEntry.getValue();
            for (String s : keyVal) {
                System.out.println("val is " + s);
            }
        }

    }

}
